import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_danli.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/enum/agree.dart';
import 'package:love_app/enum/sex.dart';
import 'package:love_app/model/dynamic_user_info_model.dart';
import 'package:love_app/pages/community/common_ui/content_ui.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/providers/user_center_provider.dart';
import 'package:love_app/service/comment_details_api.dart';
import 'package:love_app/service/dynamic_center_api.dart';
import 'package:love_app/style/space_header.dart.dart';
import 'package:provider/provider.dart';
import 'package:love_app/model/community_model.dart' as CTYModel;

class UserCenter extends StatefulWidget {
  final int userId; // 用户id

  const UserCenter({Key key, @required this.userId}) : super(key: key);

  @override
  _UserCenterState createState() => _UserCenterState();
}

class _UserCenterState extends State<UserCenter> {
  int userId;
  ShareProvider _shareProvider; // 保存全局共享数据
  UserCenterProvider _userCenterProvider; // 保存当前userID对应的数据
  EasyRefreshController _easyRefreshController; // 加载控制器
  ScrollController _scrollController; // 滚动条监听控制器
  var _getUserInfoFuture; // 获取用户信息(在构建函数之外调用Future,使其在不会发生重构)

  @override
  void initState() {
    super.initState();
    userId = widget.userId;
    _easyRefreshController = EasyRefreshController();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _userCenterProvider =
        Provider.of<UserCenterProvider>(context, listen: false);
    if (userId != _userCenterProvider.userId) {
      _userCenterProvider.clean();
    }
    _getUserInfoFuture = _getUserInfo();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _addlistenOffset();
    return FutureBuilder(
      future: _getUserInfoFuture,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          DynamicUserInfoModel dynamicCenterModel = snapshot.data;
          var v = dynamicCenterModel.data;
          return _futureBuildWidget(v.nickName, v.headImg, v.follower,
              v.followers, v.agree, v.sex, v.isFollower);
        }
        return _futureBuildWidget("", "", 0, 0, 0, 0, 0);
      },
    );
  }

  // 滚动条监听初始化
  void _addlistenOffset() {
    _scrollController =
        ScrollController(initialScrollOffset: _userCenterProvider.offset);
    _scrollController.addListener(() {
      _userCenterProvider.offset = _scrollController.offset;
    });
  }

  // 获取个人信息
  _getUserInfo() async {        
    var model = await DynamicCenterApi.dynamicUserInfo(userId, _shareProvider.token);
    return model;
  }

  // 异步容器没有完成或者加载完成要显示widget
  Widget _futureBuildWidget(String title, String imgUrl, int follower,
      int followers, int agreeNum, int sexNum, int isFollower) {
    Sex sex = IntToSex.getSex(sexNum);
    String userSex = sex == Sex.boy ? " · 男" : " · 女";
    String titleText = title.length > 0 ? title + userSex : "加载中...";
    return Scaffold(
      backgroundColor: Color.fromRGBO(137, 137, 137, 1),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 1.5,
        leading: IconButton(
            icon: Icon(
              Icons.keyboard_arrow_left,
              color: _shareProvider.textColor,
            ),
            onPressed: () {
              Navigator.pop(context);
            }),
        title: Text(
          titleText,
          style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 36),
        ),
        centerTitle: true,
      ),
      body: _body(imgUrl, follower, followers, agreeNum, sexNum, isFollower),
    );
  }

  // 页面内容
  Widget _body(String imgUrl, int follower, int followers, int agreeNum,
      int sexNum, int isFollower) {
    return Container(
      width: Su().w(750),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          // 个人信息栏目
          _userInfo(imgUrl, follower, followers, agreeNum, sexNum, isFollower),
          // 个人动态
          Expanded(
            child: _dynamicCenten(),
          ),
        ],
      ),
    );
  }

  // 个人信息栏目
  Widget _userInfo(String imgUrl, int follower, int followers, int agreeNum,
      int sexNum, int isFollower) {
    return Container(
      width: Su().w(750),
      height: Su().h(183),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          _headerIma(imgUrl),
          _userData(follower, followers, agreeNum, sexNum, isFollower),
        ],
      ),
    );
  }

  // 右边的数据
  Widget _userData(
      int follower, int followers, int agreeNum, int sexNum, int isFollower) {
    return Container(
      width: Su().w(400),
      // height: Su().w(112),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _userTopData(follower, followers, agreeNum),
          _userButtom(agreeNum, sexNum, isFollower),
        ],
      ),
    );
  }

  // 上边的数据
  Widget _userTopData(int follower, int followers, int agree) {
    return Container(
      width: Su().w(400),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          _userTopDataItem("关注", follower),
          _userTopDataItem("粉丝", followers),
          _userTopDataItem("被羡慕", agree),
        ],
      ),
    );
  }

  // 按钮
  Widget _userButtom(int agreeNum, int sexNum, int isFollower) {
    Agree agree = IntToAgree.toAgree(isFollower);
    Sex sex = IntToSex.getSex(sexNum);
    String text = agree == Agree.hasAgree ? "已关注" : "关注";
    Color bgColor = Color.fromRGBO(221, 221, 221, 1);
    if (agree == Agree.noAgree) {
      bgColor = sex == Sex.boy
          ? Color.fromRGBO(130, 190, 255, 1)
          : Color.fromRGBO(233, 140, 166, 1);
    }
    return InkWell(
      onTap: () async {
        bool success = await CommentDetailsApi()
            .followersUser(_shareProvider.token, userId);
        if (success == true && agree == Agree.hasAgree) {
          SuDialog.showToast("取消关注成功");
        } else {
          SuDialog.showToast("关注成功");
        }
        // setState(() {});
      },
      child: Container(
        alignment: Alignment.center,
        width: Su().w(367),
        height: Su().h(44),
        margin: EdgeInsets.only(
          top: Su().h(15),
        ),
        decoration: BoxDecoration(
            color: bgColor, borderRadius: BorderRadius.circular(Su().w(22))),
        child: Text(
          text,
          style: Su().textStyle(Colors.white, 22),
        ),
      ),
    );
  }

  // 每一个item
  Widget _userTopDataItem(String title, int numData) {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text(numData.toString(),
              style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 36)),
          Text(title,
              style: Su().textStyle(Color.fromRGBO(128, 128, 128, 1), 24)),
        ],
      ),
    );
  }

  // 左边的头像
  Widget _headerIma(String imgUrl) {
    Widget image = imgUrl.length > 0
        ? Image.network(
          imgUrl,
          fit: BoxFit.cover,
        )
        : Image.asset("images/home_page_img/love_tree.png");
    return Container(
      width: Su().w(113.7),
      height: Su().w(113.7),
      child: ClipOval(
        child: image,
      ),
    );
  }

  Widget _dynamicCenten() {
    List<CTYModel.Data> allItemData = _userCenterProvider.getAllItem();
    return EasyRefresh.custom(
        header: SpaceHeader(),
        controller: _easyRefreshController,
        firstRefresh: _userCenterProvider.isFirst,
        scrollController: _scrollController,
        bottomBouncing: true,
        enableControlFinishLoad: true,
        onRefresh: () async {
          // 触发下拉加载
          _userCenterProvider.clean();
          setState(() {});
          _onLoad();
        },
        onLoad: () async {
          // 触发上拉加载
          await _onLoad();
          _userCenterProvider.isFirst = false;
        },
        slivers: <Widget>[
          _sliver(allItemData),
        ],
      );
  }

  // 获取个人动态
  Future _onLoad() async {
    if (_userCenterProvider.isEndPage == false) {
      CTYModel.CommunityModel communityModel =
          await DynamicCenterApi.dynamicUserCenter(
              userId, _shareProvider.token, _userCenterProvider.page);
      if (communityModel.data.isEmpty == true) {
        _userCenterProvider.isEndPage = true;
        _easyRefreshController.finishLoad(success: true, noMore: true);
      } else {
        _userCenterProvider.page++;
        communityModel.data.forEach((item) {
          _userCenterProvider.setAllItem(item.id, item);
        });
        setState(() {});
        _easyRefreshController.finishLoad(success: true, noMore: false);
      }
    } else {
      _easyRefreshController.finishLoad(success: true, noMore: true);
    }
  }

    // 页面的slivers
  Widget _sliver(List<CTYModel.Data> allItemData) {
    if (allItemData.length == 0) {
      return SliverList(
        delegate: SliverChildListDelegate(
          [
            _sliverLenghtIsZero(),
          ],
        ),
      );
    }

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          int id = allItemData[index].id; // 数据库对应的id
          Widget widgetItem = BuildArticleItem(
            textShowAll: false,
            showImages: _userCenterProvider.showImages(id),
            token: _shareProvider.token,
            isAttention: false,
            uid: _shareProvider.uid,
            isNextPage: true,
            provider: _userCenterProvider,
            providerType: "userCenter",
            itemData: allItemData[index],
          );
          return InkWell(
            onTap: () {
              // Application.router.navigateTo(context, "/detailsItem?itemID=$id");
            },
            child: widgetItem,
          );
        },
        childCount: allItemData.length,
      ),
    );
  }

    // 当长度为零的时候页面
  Widget _sliverLenghtIsZero() {
    return Center(
      child: Container(
        padding: EdgeInsets.only(
          top: Su().h(100),
        ),
        child: Column(
          children: <Widget>[
            Image.asset(
              "images/other/attention_null.png",
            ),
            Text(
              "暂无内容",
              style: Su().textStyle(Color.fromRGBO(128, 128, 128, 1), 24),
            ),
          ],
        ),
      ),
    );
  }
}